﻿$(document).ready(Page_Load);

var rowdata;
var alertdata;
var filedata;

var displayarchived;

var $dialog;

function Page_Load(e) {
    displayarchived = false;

    $('.button').button();

    LoadProject(id);

    GetEmails(id);

    $('#btnAlertEmails').click(function () {
        AddEmail(id);
    });

    $('#btnProperties').click(function () {
        EditProject(id);
    });

    $('#btnActivate').click(function () {
        ActivateProject(id);
    });

    $('#btnArchivedFiles').click(function () {
        if (displayarchived) {
            displayarchived = false;
            LoadEmails(id, displayarchived);
            $('#imgArchived').attr("src", "/Images/filecabinet_red.png");
            $('#imgArchived').attr("title", "View Archived Files");
            $('#imgArchived').attr("alt", "View Archived Files");
        }
        else {
            displayarchived = true;
            LoadEmails(id, displayarchived);
            $('#imgArchived').attr("src", "/Images/filecabinet_green.png");
            $('#imgArchived').attr("title", "View Current Files");
            $('#imgArchived').attr("alt", "View Current Files");
        }
    });
    
}

function LoadProject(id) {
    var webMethodParams = JSON.stringify({ ProjectId: id });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Project.aspx/GetProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: LoadProject_Success,
                error: LoadProject_Error
            });
}

function LoadProject_Success(data, textStatus, XMLHttpRequest) {
    rowdata = data.d;

    if (rowdata.length == 1) {
        var item = rowdata[0];

        document.title = item["Name"];

        //$('#project-title').html(item["Name"]);
        //$('#project-description').html(item["Description"]);

        if (item["ActiveInd"] == "True") {
            //$('#btnActivate .ui-button-text').text("Deactivate Project");
            $('#imgActivate').attr("src", "/Images/green_button.png");
            $('#imgActivate').attr("title", "Deactivate Project");
            $('#imgActivate').attr("alt", "Deactivate Project");
        }
        else {
            //$('#btnActivate .ui-button-text').text("Activate Project");
            $('#imgActivate').attr("src", "/Images/red_button.png");
            $('#imgActivate').attr("title", "Activate Project");
            $('#imgActivate').attr("alt", "Activate Project");
        }
    }
}

function LoadProject_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjects", 100);
    alert("An error occurred loading the user project. Error: " + XMLHttpRequest);

}

function GetEmails(id) {
    $("#list2").jqGrid(
        {
            datatype: "local",
            colNames: ['', '', 'Date', 'File Name', 'From', 'Subject', ''],
            colModel: [
                { name: 'act', index: 'act', width: 34, sortable: false, align: 'center' },
                { name: 'id', index: 'id', width: 55, search: false, hidden: true, editable: false },
   		        { name: 'EntryDt', index: 'EntryDt', width: 125, editable: false },
                { name: 'FileName', index: 'FileName', width: 200, editable: false },
                { name: 'EmailAddress', index: 'EmailAddress', width: 200, editable: false },
                { name: 'Subject', index: 'Subject', width: 200, editable: false },
   		        { name: 'act2', index: 'act2', width: 74, sortable: false, formatter: ButtonFormatter}
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#pager2',
            sortname: 'EntryDt',
            viewrecords: true,
            sortorder: "desc",
            caption: "Files",
            height: 250,
            width: "100%",
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#list2").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];

                    download = "<img class=\'gridaction\' src=\'/Images/112_ArrowCurve_Blue_Right_32x32_72.png\' alt=\'Download\' title=\'Download\' onclick=\"DownloadFile('" + cl + "');\"/>";
                    //archive = "<img class=\'gridaction\' src=\'/Images/filecabinet.png\' alt=\'Archive\' title=\'Archive\' onclick=\"UpdateEmail('" + cl + "', true, null);\"/>";
                    //de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteFile('" + cl + "', null, true);\"/>";
                    //$("#list2").jqGrid('setRowData', ids[i], { act: download, act2: archive + de });
                    $("#list2").jqGrid('setRowData', ids[i], { act: download });
                }
            }
        });

    $("#list2").jqGrid('navGrid', '#pager2', { edit: false, add: false, del: false, beforeRefresh: function () { LoadEmails(id, displayarchived); } })

    LoadEmails(id, displayarchived);
}

function ButtonFormatter(cellvalue, options, rowObject) {
    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteFile('" + options["rowId"] + "', null, true);\"/>";

    if (!displayarchived) {
        archive = "<img class=\'gridaction\' src=\'/Images/filecabinet.png\' alt=\'Archive\' title=\'Archive\' onclick=\"UpdateEmail('" + options["rowId"] + "', true, null);\"/>";
        return archive + de
    }
    else {
        archive = "<img class=\'gridaction\' src=\'/Images/filecabinet.png\' alt=\'Un-Archive\' title=\'Un-Archive\' onclick=\"UpdateEmail('" + options["rowId"] + "', false, null);\"/>";
        return archive + de
    }
}


function LoadEmails(id, displayarchived) {
    var webMethodParams = JSON.stringify({ ProjectId: id, ArchivedInd: displayarchived });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Project.aspx/GetEmails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: LoadEmails_Success,
                error: LoadProject_Error
            });
}

function LoadEmails_Success(data, textStatus, XMLHttpRequest) {
    filedata = data.d;
    BindGrid($("#list2"), filedata, "FileId", 1);

    var ids = $("#list2").jqGrid('getDataIDs');
    for (var i = 0; i < ids.length; i++) {
        var cl = ids[i];

        download = "<img class=\'gridaction\' src=\'/Images/112_ArrowCurve_Blue_Right_32x32_72.png\' alt=\'Download\' title=\'Download\' onclick=\"DownloadFile('" + cl + "');\"/>";
        if (!displayarchived) {
            archive = "<img class=\'gridaction\' src=\'/Images/filecabinet.png\' alt=\'Archive\' title=\'Archive\' onclick=\"UpdateEmail('" + cl + "', true, null);\"/>";
        }
        de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteFile('" + cl + "', null, true);\"/>";
        $("#list2").jqGrid('setRowData', ids[i], { act: download, act2: archive + de });
    }
}

function DownloadFile(fileid) {
    $dialog = $('<div></div>')
		.html('Please wait while the file is prepared for download.')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    title: 'Downloading File.'
		});
	$dialog.dialog('open');

	setInterval("CheckDownload()", 1000);
    $('#download-frame').attr("src", "/Download.ashx?id=" + fileid);

}

function CheckDownload() {
    var iframe = document.getElementById('download-frame');

    if (iframe != null) {
        if (iframe.contentDocument != null) {
            $dialog.dialog('close');
            clearInterval(this);
        }
    }

}


function DeleteFile(fileid) {
    var data = filedata[$("#list2").jqGrid('getInd', fileid, false) - 1];
    var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + data["FileName"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteFileConfirmed(fileid);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
    $dialog.dialog('open');
}

function DeleteFileConfirmed(fileid) {
    UpdateEmail(fileid, null, true);
}


function UpdateEmail(fileid, archivedind, deletedind) {
    var webMethodParams = JSON.stringify({ FileId: fileid, Archived: archivedind, Deleted: deletedind });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Project.aspx/UpdateEmail",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: UpdateEmail_Success,
                error: UpdateEmail_Error
            });

}

function UpdateEmail_Success(data, textStatus, XMLHttpRequest) {
    LoadEmails(id, displayarchived);
}

function UpdateEmail_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "UpdateEmail", 100);
    alert("An error occurred updating the project. Error: " + XMLHttpRequest);

}


function AddEmail(project) {
    currentid = project;

    $("#dialog-maintainalerts").dialog({
        resizable: false,
        height: 410,
        width: 505,
        modal: true,
        buttons: {
            'Done': function () {
                $(this).dialog('close');
            }
        },
        close: function () {

        }
    });

    $("#addemail").button();
    $("#addemail").click(function () {
        InsertEmail(project);
    });

    $("#alertlist").jqGrid(
        {
            datatype: "local",
            colNames: ['', 'Email', ''],
            colModel: [
                { name: 'id', index: 'id', width: 55, search: false, hidden: true, editable: false },
   		        { name: 'Email', index: 'email', width: 350, editable: false },
                { name: 'act2', index: 'act2', width: 38, sortable: false }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#alertpager',
            sortname: 'Name',
            viewrecords: true,
            sortorder: "desc",
            caption: "",
            height: 145,
            width: "465",
            editurl: 'somepage.aspx',
            gridComplete: function () {
                var ids = $("#alertlist").jqGrid('getDataIDs');
                for (var i = 0; i < ids.length; i++) {
                    var cl = ids[i];
                    //                    lock = "<img class=\'gridaction\' src=\'/Images/Encrypt.png\' alt=\'Lock or Unlock\' title=\'Lock or Unlock\' onclick=\"UnlockUser('" + cl + "');\"/>";
                    //activate = "<img class=\'gridaction\' src=\'/Images/base_checkmark_32.png\' alt=\'Activate/Deactivate\' title=\'Activate/Deactivate\' onclick=\"ActivateProject('" + cl + "');\"/>";
                    //ed = "<img class=\'gridaction\' src=\'/Images/Page.png\' alt=\'Edit\' title=\'Edit\' onclick=\"EditProject('" + cl + "');\"/>";
                    de = "<img class=\'gridaction\' src=\'/Images/delete.png\' height=32 width=32 alt=\'Delete\' title=\'Delete\' onclick=\"DeleteAlertEmail('" + cl + "');\"/>";
                    //addalert = "<img class=\'gridaction\' src=\'/Images/Users.png\' height=32 width=32 alt=\'Add Alert Email\' title=\'Add Alert Email\' onclick=\"AddEmail('" + cl + "');\"/>";
                    $("#alertlist").jqGrid('setRowData', ids[i], { act2: de });
                }
            }
        });

    $("#alertlist").jqGrid('navGrid', '#alertpager', { edit: false, add: false, del: false, beforeRefresh: function () { GetAlertEmails(project); } });

    GetAlertEmails(project);
}

function GetAlertEmails(project) {
    var webMethodParams = JSON.stringify({ ProjectId: project });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Projects.aspx/GetAlertEmails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: LoadAlertEmails_Success,
                error: LoadAlertEmails_Error
            });
}

function LoadAlertEmails_Success(data, textStatus, XMLHttpRequest) {
    alertdata = data.d;
    BindGrid($("#alertlist"), alertdata, "ProjectAlertEmailId", 1);
}

function LoadAlertEmails_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjectAlertEmails", 100);
    alert("An error occurred loading the project emails. Error: " + XMLHttpRequest);
}

function RefreshAlertGrid(data, textStatus, XMLHttpRequest) {
    $(".error").html("");
    $(".ui-state-error").removeClass("ui-state-error");

    if (data.d == "" || data.d == null) {
        GetAlertEmails(currentid);
    }
    else {
        alert(data.d);
    }
}

function InsertEmail(project) {
    var email = $('#alertemail');

    var bValid = true;

    bValid = bValid && checkRegexp(email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "Enter a valid email address.  eg. user@email.com");

    bValid = bValid && checkLength(email, "email address", 6);

    if (bValid) {
        var webMethodParams = JSON.stringify({ ProjectId: project, Email: email.val() });
        $('#alertemail').val("");
        $.ajax(
                {
                    type: "POST",
                    async: true,
                    url: "Projects.aspx/AddAlertEmails",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: webMethodParams,
                    success: RefreshAlertGrid,
                    error: LoadAlertEmails_Error
                });

    }
}

function DeleteAlertEmail(alertid) {
    var data = alertdata[$("#alertlist").jqGrid('getInd', alertid, false) - 1];
    var $dialog = $('<div></div>')
		.html('Please confirm the delete request (' + data["Email"] + ').')
		.dialog({
		    autoOpen: false,
		    resizable: false,
		    height: 200,
		    width: 400,
		    modal: true,
		    buttons: {
		        'Yes': function () {
		            DeleteAlertEmailConfirmed(alertid);
		            $(this).dialog('close');
		        },
		        'No': function () {
		            $(this).dialog('close');
		        }
		    },
		    title: 'Confirm Delete'
		});
    $dialog.dialog('open');
}

function DeleteAlertEmailConfirmed(alertid) {

    var webMethodParams = JSON.stringify({ ProjectAlertEmailId: alertid });
    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Projects.aspx/DeleteAlertEmails",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: RefreshAlertGrid,
                error: LoadAlertEmails_Error
            });

}

function EditProject(project) {
    var item = rowdata[0];

    $("#name").val(item["Name"]);
    $("#description").val(item["Description"]);
    
    $("#dialog-newproject").dialog({
        resizable: false,
        height: 320,
        width: 505,
        modal: true,
        buttons: {
            'Update': function () {

                var data = rowdata[0];

                var projectname = $('#name');
                var projectdescription = $('#description');

                var webMethodParams = JSON.stringify({ ProjectId: project, ProjectName: projectname.val(), ProjectDescription: projectdescription.val(), ActiveInd: data["ActiveInd"] });

                var bValid = true;

                bValid = bValid && checkLength(projectname, "Project Name", 5);

                if (bValid) {
                    $.ajax(
                {
                    type: "POST",
                    async: true,
                    url: "Projects.aspx/UpdateProject",
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    data: webMethodParams,
                    success: EditProject_Success,
                    error: EditProject_Error
                });


                }
            },
            'Cancel': function () {
                $(this).dialog('close');
            }
        },
        close: function () {
            $('input').val("");

            $(".error-container").removeClass("ui-state-error ui-corner-all");
            $(".error").html("");

            $('input').removeClass("ui-state-error");
        }
    });
}

function EditProject_Success(data, textStatus, XMLHttpRequest) {
    $("#dialog-newproject").dialog('close');
    LoadProject(id);
}

function EditProject_Error(XMLHttpRequest, textStatus, errorThrown) {
    Log(XMLHttpRequest, "LoadProjectAlertEmails", 100);
    alert("An error occurred loading the project emails. Error: " + XMLHttpRequest);
}

function ActivateProject(project) {
    var data = rowdata[0];

    var name = data["Name"];
    var description = data["Description"];
    var active = data["ActiveInd"];
    
    var webMethodParams = JSON.stringify({ ProjectId: project, ProjectName: name, ProjectDescription: description, ActiveInd: active });

    $.ajax(
            {
                type: "POST",
                async: true,
                url: "Projects.aspx/ActivateProject",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                data: webMethodParams,
                success: EditProject_Success,
                error: EditProject_Error
            });
}